#!/usr/bin/python
import sys, os, re, time
################################################################################
################################################################################
class Params:
   verbose = True
   cleanup = True
   xleaf   = False
   trial   = False
   def __init__( self, mtxFile ):
      
      self.formats = [ 'RMA', 'QTS', 'NZD', 'CSR', 'COO' ]
      self.degrees = [ 2, 4, 8 ]
      
      dagMtxHomeEnvName = 'DAGMTX_HOME_DIR'
      
      if not dagMtxHomeEnvName in os.environ:
         print 'Before using ' + sys.argv[0] + ', you need to set the environment variable "' + dagMtxHomeEnvName + '"'
         print 'to point to the home directory for this project.'
         sys.exit( -1 )
      
      self.qtsHomeDir = os.environ[ dagMtxHomeEnvName ]
      self.mtxFile = mtxFile
   

################################################################################
################################################################################
def PrintTimeStamp():
   theTime = time.localtime()
   yr  = '%04d' % theTime.tm_year
   mon = '%02d' % theTime.tm_mon
   day = '%02d' % theTime.tm_mday
   hr  = '%02d' % theTime.tm_hour
   mt  = '%02d' % theTime.tm_min
   sec = '%02d' % theTime.tm_sec
   print '...', '/'.join( [yr, mon, day] ), ':'.join( [hr, mt, sec] )
   sys.stdout.flush()

def SystemWrapperPipelined( cmd, verbose, trial = False ):
   if verbose:
      PrintTimeStamp()
      print '... os.popen(', cmd, ')'
      sys.stdout.flush()
   if not trial:
      FH = os.popen( cmd )
      output = [ line.rstrip() for line in FH.readlines() ]
      FH.close()
      return output
   return []

def SystemWrapper( cmd, verbose, trial = False ):
   dt = 0
   if verbose:
      PrintTimeStamp()
      print '... os.system(', cmd, ')'
      sys.stdout.flush()
   if trial:
      status = 0
   else:
      t0 = time.time()
      status = os.system( cmd )
      t1 = time.time()
      dt = t1 - t0
   assert status == 0
   if verbose:
      print '...', dt, 'seconds elapsed during system call.'
   return dt

def RemoveWrapper( fn, verbose, trial = False ):
	if verbose:
		PrintTimeStamp()
		print '... os.remove(', fn, ')'
		sys.stdout.flush()
	if not trial:
		os.remove( fn )

################################################################################
################################################################################
( progPath, progName ) = os.path.split( sys.argv[0] )
if len( sys.argv ) < 2:
   print 'Usage:', progName, '<mtxFile>'
   sys.exit( -1 )

params = Params( sys.argv[1] )

for format in params.formats:
   for degree in params.degrees:
      cmd = os.path.join( progPath, 'BuildDagMtx.py %s %s %d 1' % ( format, params.mtxFile, degree ) )
      SystemWrapper( cmd, params.verbose, trial = False )
